﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;

namespace WXTao
{
    class JDTui
    {
        private string appid = "2009220956504952";
        private string appkey = "8f7e540c8689f53ffdf032a5ec93e3f8";

        private string unionid = "1001890482";
        private string positionid = "3002846911";

        public JDTui() {
            
        }

        public string getData(string url, string param)
        {
            string api_url = url.EndsWith(@"?") ? url.Trim() : url.Trim() + @"?";
            string api_params = param.Trim();
           
            api_url += api_params;
            try
            {
                using (var client = new HttpClient())
                {
                    var responseString = client.GetStringAsync(api_url);
                    return responseString.Result;
                }
            }
            catch (Exception e)
            {
                return e.Message.ToString();
            }
        }

        public static string PostData(string url, string param)
        {
            string result = "";
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded";

            #region 添加Post 参数
            //StringBuilder builder = new StringBuilder();
            //int i = 0;
            //foreach (var item in dic)
            //{
            //    if (i > 0)
            //        builder.Append("&");
            //    builder.AppendFormat("{0}={1}", item.Key, item.Value);
            //    i++;
            //}
            //byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
            byte[] data = Encoding.UTF8.GetBytes(param);
            req.ContentLength = data.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(data, 0, data.Length);
                reqStream.Close();
            }
            #endregion

            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            Stream stream = resp.GetResponseStream();
            //获取响应内容
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }
            return result;
        }

        public string get_today_top()
        {
            string url = "http://japi.jingtuitui.com/api/today_top";
            string param = "appid="+appid+"&appkey="+appkey+"&page=1&num=10";
            return PostData(url,param);
        }

        public string get_goods_link(long goods_id, string discount_link)
        {
            string url = "http://japi.jingtuitui.com/api/get_goods_link";
            string param = "appid=" + appid + "&appkey=" + appkey +
                "&unionid=" + unionid + "&positionid=" + positionid +
                "&gid=" + goods_id + "&coupon_url=" + discount_link;

            return PostData(url, param);

        }

        public string getCpsUrl(string materialId,string couponUrl)
        {
            string url = "http://api.web.21ds.cn/jingdong/doItemCpsUrl";
            string keyid = "J4727488537770976";
            return getData(url, "apkey=99b18858-6f59-2516-b812-011bd61defd9&materialId="+
                materialId + "&key_id="+keyid+ "&couponUrl="+ couponUrl);
        }

        public JDData[] getSuggest(int num)
        {
            List<JDData> datas = new List<JDData>();
            string top_data = get_today_top();
            for (int i = 0; i < num; i++)
            {
                JDData jd = new JDData();
                jd.ErrorMsg = "";
                Random ran = new Random();
                int RandKey = ran.Next(0, 9);

                try
                {
                    JObject jObj = JObject.Parse(top_data);
                    if (jObj["return"] != null && jObj["return"].ToString().Equals("0"))
                    {
                        JArray list_array = JArray.Parse(jObj["result"].ToString());
                        jd.Goods_id = long.Parse(list_array[RandKey]["goods_id"].ToString());
                        jd.Goods_img = list_array[RandKey]["goods_img"].ToString();
                        jd.Goods_name = list_array[RandKey]["goods_name"].ToString();
                        jd.Goods_content = list_array[RandKey]["goods_content"].ToString();
                        jd.Discount_link = list_array[RandKey]["discount_link"].ToString();
                        jd.Goods_link = list_array[RandKey]["goods_link"].ToString();
                        Thread.Sleep(500);
                        //string data = get_goods_link(jd.Goods_id, jd.Discount_link);
                        string data = getCpsUrl(HttpUtility.UrlEncode(jd.Goods_link), HttpUtility.UrlEncode(jd.Discount_link));
                        jObj = JObject.Parse(data);
                        if (jObj["code"] != null && jObj["code"].ToString().Equals("200"))
                        {
                            jObj = JObject.Parse(jObj["data"].ToString());
                            jd.CouponClickUrl = jObj["shortURL"].ToString();
                            datas.Add(jd);
                        }
                        else
                        {
                            jd.ErrorMsg = jObj["msg"].ToString();
                            datas.Add(jd);
                        }
                    }
                    else
                    {
                        jd.ErrorMsg = jObj["msg"].ToString();
                        datas.Add(jd);
                    }

                }
                catch (Exception e)
                {
                    jd.ErrorMsg = e.Message.ToString();
                    datas.Add(jd);
                    continue;
                }
                
            }

            return datas.ToArray();
        }
    }
}
